package com.gc.web.controller.business;

import cn.hutool.core.date.DateUtil;
import com.gc.business.domain.CommunityManage;
import com.gc.business.domain.ElevatorFault;
import com.gc.business.domain.ElevatorInfo;
import com.gc.business.service.*;
import com.gc.common.annotation.Log;
import com.gc.common.base.Result;
import com.gc.common.config.Global;
import com.gc.common.enums.BusinessType;
import com.gc.common.support.Convert;
import com.gc.common.utils.DateUtils;
import com.gc.common.utils.StringUtils;
import com.gc.common.utils.poi.ExcelUtil;
import com.gc.framework.util.ShiroUtils;
import com.gc.framework.web.base.BaseController;
import com.gc.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 电梯故障 控制层
 *
 * @author hruiyan
 * @date 2020-11-16
 */
@Slf4j
@Controller
@RequestMapping("/business/elevatorFault")
public class ElevatorFaultController extends BaseController {
    private String prefix = "business/elevatorFault" ;

    @Autowired
    private ISysUserService userService;

    private final IElevatorFaultService elevatorFaultService;
    private final IUserElevatorAllotService userElevatorAllotService;
    private final IElevatorInfoService elevatorInfoService;
    private final ICommunityManageService communityManageService;
    private final IElevatorRepairService elevatorRepairService;

    @Autowired
    public ElevatorFaultController(IElevatorFaultService elevatorFaultService,
                                   IUserElevatorAllotService userElevatorAllotService,
                                   IElevatorInfoService elevatorInfoService,
                                   ICommunityManageService communityManageService,
                                   IElevatorRepairService elevatorRepairService) {
        this.elevatorFaultService = elevatorFaultService;
        this.userElevatorAllotService = userElevatorAllotService;
        this.elevatorInfoService = elevatorInfoService;
        this.communityManageService = communityManageService;
        this.elevatorRepairService = elevatorRepairService;
    }

    /**
     * 列表页
     */
    @RequiresPermissions("business:elevatorFault:view")
    @GetMapping
    public String elevatorFault() {
        return prefix + "/elevatorFault" ;
    }

    /**
     * 历史故障列表页
     */
    @RequiresPermissions("business:elevatorFault:view")
    @GetMapping("/historyFault")
    public String historyFault() {
        return prefix + "/historyFault" ;
    }

    /**
     * 跳转立即处理页面
     */
    @GetMapping("/immediatelyHandle/{faultId}")
    public String immediatelyHandle(@PathVariable("faultId") Long faultId, ModelMap mmap) {
        ElevatorFault elevatorFault = elevatorFaultService.getById(faultId);
        mmap.put("elevatorFault", elevatorFault);
        return prefix + "/immediatelyHandle" ;
    }

    /**
     * 新增页
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add" ;
    }

    /**
     * 编辑页
     */
    @GetMapping("/edit/{faultId}")
    public String edit(@PathVariable("faultId") Long faultId, ModelMap mmap) {
        ElevatorFault elevatorFault = elevatorFaultService.getById(faultId);
        mmap.put("elevatorFault", elevatorFault);
        return prefix + "/edit" ;
    }

    /**
     * 查询电梯故障列表
     */
    @RequiresPermissions("business:elevatorFault:list")
    @PostMapping("/list")
    @ResponseBody
    public Result list(ElevatorFault elevatorFault, Integer type) {
        if (StringUtils.isNotNull(type)) {
            if (type == 1) {//是否查询今日故障
                elevatorFault.setIsNowDay("1");
            }
        }

        Long attrId = getAttrId();
        Boolean ifCompany = userService.ifCompanyRole(attrId);
        if(ifCompany){
            elevatorFault.setCompanyId(attrId);
            startPage();
            List<ElevatorFault> list = elevatorFaultService.selectElevatorFaultList(elevatorFault);
            return Result.success(getDataTable(list));
        }else{
            return Result.success(getDataTable(new ArrayList<ElevatorFault>()));
        }
    }

    /**
     * 新增保存电梯故障
     */
    @RequiresPermissions("business:elevatorFault:add")
    @Log(title = "电梯故障", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public Result addSave(ElevatorFault elevatorFault) {
        elevatorFaultService.save(elevatorFault);
        return Result.success();
    }

    /**
     * 修改保存电梯故障
     */
    @RequiresPermissions("business:elevatorFault:edit")
    @Log(title = "电梯故障", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public Result editSave(ElevatorFault elevatorFault) {
        elevatorFaultService.updateById(elevatorFault);
        return Result.success();
    }

    /**
     * 立即处理电梯故障
     */
    @RequiresPermissions("business:elevatorFault:edit")
    @Log(title = "电梯故障", businessType = BusinessType.UPDATE)
    @PostMapping("/immediatelyHandle")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result immediatelyHandle(ElevatorFault elevatorFault) {
        ElevatorFault faultById = elevatorFaultService.getById(elevatorFault.getFaultId());
        //处理人
        elevatorFault.setDisposeMan(ShiroUtils.getSysUser().getUserName());
        elevatorFault.setDisposeAvatar(ShiroUtils.getSysUser().getAvatar() == null ? Global.getConfig("gc.default_avatar_url") : ShiroUtils.getSysUser().getAvatar());
        //使用不当
        if (elevatorFault.getDisposeOpin().equals("0")) {
            elevatorFault.setDisposeState("2");
            //需要维修
        } else if (elevatorFault.getDisposeOpin().equals("1")) {
            faultById.setDisposeState("1");
            //派单人
            faultById.setDispatchPeople(ShiroUtils.getSysUser().getUserName());
            //派单时间
            faultById.setDispatchDate(DateUtil.date());
            //派单人头像
            if (StringUtils.isNull(ShiroUtils.getSysUser().getAvatar())) {
                faultById.setDispatchAvatar(Global.getConfig("gc.default_avatar_url"));
            }else{
                faultById.setDispatchAvatar(ShiroUtils.getSysUser().getAvatar());
            }
            faultById.setDisposeOpin("1");
            faultById.setFaultMessage(elevatorFault.getFaultMessage());

            //添加保存维修单
            elevatorRepairService.saveElevatorRepairByFault(faultById);
            elevatorFault.setDisposeState("1");
            //设备问题
        } else if (elevatorFault.getDisposeOpin().equals("2")) {
            elevatorFault.setDisposeState("5");
        }

        //更改小区、电梯状态
        ElevatorInfo elevatorInfo = elevatorInfoService.getById(faultById.getElevatorId());
        if (elevatorInfo.equals("0")) {
            elevatorInfo.setIsFault("1");
            elevatorInfoService.saveOrUpdate(elevatorInfo);
        }
        CommunityManage communityManage = communityManageService.getById(elevatorInfo.getBelongCommunity());
        if (communityManage != null && communityManage.getIsFault().equals("0")) {
            communityManage.setIsFault("1");
            communityManageService.saveOrUpdate(communityManage);
        }
        elevatorFaultService.updateById(elevatorFault);
        return Result.success();
    }

    /**
     * 删除电梯故障
     */
    @RequiresPermissions("business:elevatorFault:remove")
    @Log(title = "电梯故障", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public Result remove(String ids) {
        Long[] longIds = Convert.toLongArray(ids);
        elevatorFaultService.removeByIds(Arrays.asList(longIds));
        return Result.success();
    }

    /**
     * 导出电梯故障列表
     */
    @RequiresPermissions("business:elevatorFault:export")
    @PostMapping("/export")
    @ResponseBody
    public Result export(ElevatorFault elevatorFault) {
        List<ElevatorFault> list = elevatorFaultService.list(elevatorFault);
        ExcelUtil<ElevatorFault> util = new ExcelUtil<>(ElevatorFault.class);
        util.exportExcel(list, "elevatorFault");
        return Result.success();
    }
}
